using AutoMapper;
using B.S.RbacData.Infrastructure;
using MediatR;
using Microsoft.EntityFrameworkCore;
using SupplierCustomerManagement.Domain.Entities;
using B.S.RbacData.ErrorCode;
using SupplierCustomerManagement.Read.API.Applications.Commands.attachments;
using SupplierCustomerManagement.Read.API.Dtos;

namespace SupplierCustomerManagement.Read.API.Applications.CommandHandlters.attachments
{
    /// <summary>
    /// 获取附件列表查询处理器
    /// </summary>
    public class GetAttachmentsQueryHandler : IRequestHandler<GetAttachmentsQuery, ApiPaging<AttachmentListDto>>
    {
        private readonly IBaseRepository<Attachment> _attachmentRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<GetAttachmentsQueryHandler> _logger;

        public GetAttachmentsQueryHandler(
            IBaseRepository<Attachment> attachmentRepository,
            IMapper mapper,
            ILogger<GetAttachmentsQueryHandler> logger)
        {
            _attachmentRepository = attachmentRepository;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 处理获取附件列表查询
        /// </summary>
        /// <param name="request">查询请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>分页查询结果</returns>
        public async Task<ApiPaging<AttachmentListDto>> Handle(GetAttachmentsQuery request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始查询附件列表，页码: {PageIndex}, 每页大小: {PageSize}", 
                    request.PageIndex, request.PageSize);

                // 构建查询条件
                var query = _attachmentRepository.GetAll()
                    .Where(a => !a.IsDeleted); // 排除已删除的记录

                // 应用筛选条件
                query = ApplyFilters(query, request);


                // 获取总数量
                var totalCount = await query.CountAsync(cancellationToken);

                // 计算总页数
                var pageCount = (int)Math.Ceiling((double)totalCount / request.PageSize);

                // 分页查询
                var attachments = await query.OrderByDescending(a => a.CreatedTime)
                    .Skip((request.PageIndex - 1) * request.PageSize)
                    .Take(request.PageSize)
                    .ToListAsync(cancellationToken);

                // 映射到DTO
                var attachmentDtos = _mapper.Map<List<AttachmentListDto>>(attachments);

                // 格式化文件大小
                foreach (var dto in attachmentDtos)
                {
                    dto.FileSizeFormatted = FormatFileSize(dto.FileSize);
                }

                _logger.LogInformation("成功查询附件列表，总数量: {TotalCount}, 当前页数量: {CurrentPageCount}", 
                    totalCount, attachmentDtos.Count);

                return new ApiPaging<AttachmentListDto>
                {
                    code = ResultEnumCode.Ok,
                    message = "查询成功",
                    data = default,
                    TotalCount = totalCount,
                    PageCount = pageCount,
                    PageData = attachmentDtos
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询附件列表时发生异常");
                
                return new ApiPaging<AttachmentListDto>
                {
                    code = ResultEnumCode.fails,
                    message = $"查询附件列表时发生异常: {ex.Message}",
                    data = default,
                    TotalCount = 0,
                    PageCount = 0,
                    PageData = new List<AttachmentListDto>()
                };
            }
        }

        /// <summary>
        /// 应用筛选条件
        /// </summary>
        /// <param name="query">查询对象</param>
        /// <param name="request">查询请求</param>
        /// <returns>应用筛选条件后的查询对象</returns>
        private IQueryable<Attachment> ApplyFilters(IQueryable<Attachment> query, GetAttachmentsQuery request)
        {
            // 关联实体ID精确查询
            if (request.RelatedEntityId.HasValue)
            {
                query = query.Where(a => a.RelatedEntityId == request.RelatedEntityId.Value);
            }

            // 关联实体类型精确查询
            if (!string.IsNullOrWhiteSpace(request.RelatedEntityType))
            {
                query = query.Where(a => a.RelatedEntityType == request.RelatedEntityType);
            }


            return query;
        }

        
        

        /// <summary>
        /// 格式化文件大小
        /// </summary>
        /// <param name="bytes">字节数</param>
        /// <returns>格式化后的文件大小字符串</returns>
        private string FormatFileSize(long bytes)
        {
            if (bytes < 1024)
                return $"{bytes} B";
            else if (bytes < 1024 * 1024)
                return $"{bytes / 1024.0:F1} KB";
            else if (bytes < 1024 * 1024 * 1024)
                return $"{bytes / (1024.0 * 1024.0):F1} MB";
            else
                return $"{bytes / (1024.0 * 1024.0 * 1024.0):F1} GB";
        }
    }
} 